const ethers = require('ethers');
const fs = require('fs');
const {resolve} = require("path");
//调用合约的函数或者事件，不需要全部函数的定义都列出来
let abi = [{
    "inputs": [{
        "internalType": "uint256", "name": "x", "type": "uint256"
    }], "name": "set", "outputs": [], "stateMutability": "nonpayable", "type": "function"
}, {
    "inputs": [], "name": "get", "outputs": [{
        "internalType": "uint256", "name": "", "type": "uint256"
    }], "stateMutability": "view", "type": "function", "constant": true
}]

// Connect to the network
let provider = new ethers.providers.JsonRpcProvider("https://node.lingjingchain.cn");

// 地址来自上面部署的合约
let contractAddress = "0x116d572896A0af225F44fe2823584D029dA5c119";

// 使用Provider 连接合约
let contract = new ethers.Contract(contractAddress, abi, provider);

// 钱包地址的私钥；生产环境注意保密，用完可以清空
let pri_path = resolve(__dirname, '..', '.pri')
let privateKey = fs.readFileSync(pri_path).toString().trim();

// 从私钥获取一个签名器 Signer
let wallet = new ethers.Wallet(privateKey, provider);

// 使用签名器创建一个新的合约实例，它允许使用可更新状态的方法
let contractWithSigner = contract.connect(wallet);


(async () => {

// 调用前面定义的abi交易函数，需要扣除交易费。 只读函数不用这种方式调用，可以在etherscan.io网上校验合约后直接调用
    await contractWithSigner.set(8)
        .then(function (data) {
            if (data) {
                console.log("========result==set:");
                console.log(data);
            }
        }, function (error) {
            if (error) {
                console.log("========error:");
                console.log(error);
            }
        });

    await contractWithSigner
        .get()
        .then(function (data) {
            if (data) {
                console.log("========result==get:");
                console.log(data);
            }
        }, function (error) {
            if (error) {
                console.log("========error:");
                console.log(error);
            }
        });
})()